package com.my.lucky.service;

import cn.hutool.core.thread.ThreadUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.my.lucky.model.Stock;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.util.*;

public class SohuStockAPI {
    // 将搜狐代码格式转换为新浪代码格式
    private static String convertToSinaCode(String sohuCode) {
        // 从cn_600000格式转换为sh600000格式
        String number = sohuCode.substring(3); // 去掉cn_前缀
        if (number.startsWith("6")) {
            return "sh" + number;
        } else {
            return "sz" + number;
        }
    }

    // 获取实时行情（使用新浪接口）
    public static Map<String, String> getRealtimeQuote(String code) throws IOException {
        // 转换为新浪的代码格式
        String sinaCode = convertToSinaCode(code);
        String url = "http://hq.sinajs.cn/list=" + sinaCode;
        // URL u = new URL(url);
        HttpRequest httpRequest = HttpRequest.get(url);
        httpRequest.header("Referer", "https://finance.sina.com.cn");
        HttpResponse execute = httpRequest.execute();
        BufferedReader in = new BufferedReader(new InputStreamReader(execute.bodyStream(), "GBK"));
        String line = in.readLine();
        //   System.out.println(line);
        in.close();
        Map<String, String> result = new HashMap<>();
        if (line != null && line.contains("=\"")) {
            String[] parts = line.split("=\"");
            if (parts.length > 1) {
                String[] fields = parts[1].replace("\";", "").split(",");
                // 0:名称 1:今日开盘价 2:昨日收盘价 3:当前价 4:最高价 5:最低价
                if (fields.length > 6) {
                    result.put("name", fields[0]);
                    result.put("open", fields[1]);
                    result.put("pre_close", fields[2]);
                    result.put("price", fields[3]);
                    result.put("high", fields[4]);
                    result.put("low", fields[5]);
                    result.put("volume", fields[8]);
                    return result;
                }
            }
        }
        return null;
    }

    // 获取历史K线（日K）
    public static List<Stock> getHistoryKLine(String code, String start, String end) throws IOException {
        // code示例：cn_600000
        code = "cn_" + code.substring(3);
        //  System.out.println(code);
        ThreadUtil.safeSleep(200);
        String url = String.format("https://q.stock.sohu.com/hisHq?code=%s&start=%s&end=%s&stat=1&order=D&period=d&callback=historySearchHandler&rt=jsonp",
                code, start.replace("-", ""), end.replace("-", ""));
        System.out.println(url);
        URL u = new URL(url);
        BufferedReader in = new BufferedReader(new InputStreamReader(u.openStream(), "GBK"));
        String line = in.readLine();
        in.close();
        System.out.println(line);
        List<Stock> stocks = new ArrayList<>();
        if (line != null && line.contains("historySearchHandler([{")) {
            // 解析JSON格式数据
            String jsonStr = line.replace("historySearchHandler([", "").replace("])", "");
            JSONObject entries = JSONUtil.parseObj(jsonStr);
            JSONArray hq = entries.getJSONArray("hq");
            List<String[]> strings = hq.toList(String[].class);
            if (strings.size() > 0) {
                for (String[] fields : strings) {
                    // 日期,开盘,收盘,涨跌,涨幅,最低,最高,成交量,成交额,换手率
                    try {
                        String date = fields[0];
                        double open = Double.parseDouble(fields[1]);
                        double close = Double.parseDouble(fields[2]);
                        double high = Double.parseDouble(fields[6]);
                        double low = Double.parseDouble(fields[5]);
                        double volume = Double.parseDouble(fields[7]);
                        stocks.add(new Stock(code, date, close, open, high, low, volume));
                    } catch (Exception e) {
                        // skip invalid data
                    }
                }
            } else {
                System.out.println(")))))))))))))))))))))))))");
            }
        }

        // 按日期升序
        stocks.sort(Comparator.comparing(Stock::getDate));
        return stocks;
    }
} 